package vn.vfriends.payment.bean;

import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@RequestScoped
public class HomeBean implements Serializable {

    static Logger logger = LoggerFactory.getLogger(HomeBean.class);
    
    private boolean logginRequire;
    
    private boolean logginError;

    public boolean getLogginRequire() {
        return logginRequire;
    }

    public void setLogginRequire(boolean logginRequire) {
        this.logginRequire = logginRequire;
    }

    public boolean isLogginError() {
        return logginError;
    }

    public void setLogginError(boolean logginError) {
        this.logginError = logginError;
    }

    public void preRenderIndexAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (logginRequire) {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bạn phải đăng nhập để sử dụng chức năng này", ""));
            }
            if (logginError) {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Có lỗi trong quá trình đăng nhập", ""));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
    
    public void preRenderAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
            HttpSession session = request.getSession(true);
            if(session.getAttribute("LOGGED_USER") == null) {
                context.getExternalContext().redirect("index.jsf");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
}
